package org.quartz.watch;

import javax.faces.context.FacesContext;

import org.quartz.watch.dc.QWDialogController;
import org.quartz.watch.dc.QWSchedulerDialogController;

public class QWContext {
	public static final String QW_CONTEXT_INSTANCE = "QW_CONTEXT_INSTANCE";

	public static QWContext getInstance() {
		QWContext context = (QWContext)FacesContext.getCurrentInstance()
		.getExternalContext()
		.getSessionMap()
		.get(QW_CONTEXT_INSTANCE);

		if(context == null) {
			context = new QWContext();

			FacesContext.getCurrentInstance()
			.getExternalContext()
			.getSessionMap()
			.put(QW_CONTEXT_INSTANCE, context);
		}

		return context;
	}


	private <S extends QWDialogController<?>> QWDialogController<?> getDialogController(Class<S> dcInterface, String dcName)
	{
		QWDialogController<?> service = (QWDialogController<?>)FacesContext.getCurrentInstance()
		.getApplication()
		.getExpressionFactory()
		.createValueExpression(FacesContext.getCurrentInstance().getELContext(), 
				"#{"+dcName+"}", 
				dcInterface)
				.getValue(FacesContext.getCurrentInstance().getELContext());

		return service;
	}

	public QWSchedulerDialogController<?> getSchedulerDialogController() {
		return (QWSchedulerDialogController<?>)getDialogController(QWSchedulerDialogController.class, "schedulerDC");
	}
}
